import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/model/exam_question.dart';
import 'package:kxy_flutter_app/model/test.dart';
import 'package:kxy_flutter_app/model/test_result.dart';
import 'package:kxy_flutter_app/services/test_service.dart';

class TestModel with ChangeNotifier {
  Test test;
  TestResult testResult;
  TestService testService;
  int _index = 0;
  int _second;
  Timer _secondTimer;
  List<Question> questionList = new List<Question>();

  int get index => _index;
  bool get isComplete {
    for (var item in questionList) {
      if (item.userAnswer == null || item.userAnswer.isEmpty) {
        return false;
      }
    }
    return true;
  }

  Question get current {
    if (questionList == null || questionList.length == 0) return null;
    return questionList[_index];
  }

  // 1. 开始答题
  Future startTest(Test test) async {
    _index = 0;
    _second = 0;
    questionList.clear();

    if (_secondTimer != null) {
      _secondTimer.cancel();
    }

    _secondTimer = Timer.periodic(
      Duration(seconds: 1),
      (_) => _second++,
    );
    test = test;

    testService = new TestService(
      testId: test.id,
      userId: Auth.instance.userId,
    );
    questionList = await testService.getQuestionList();
    notifyListeners();
  }

  // 2. 填写答案
  void setAnswer(String answer) async {
    // 如果已完成答题，不做处理
    if (current.confirmed == true) return;

    current.userAnswer = answer;
    if (current.type != 4 /* 填空题 */) {
      notifyListeners();
    }
  }

  // 3. 提交答题选项
  Future submitAnswer() async {
    var result = await testService.submitAnswer(
      current.quesId,
      current.userAnswer,
      _second,
    );
    if (result.first == false) {
      Fluttertoast.showToast(msg: '服务器错误：答题失败！');
    } else {
      current.confirmed = true;
      _second = 0;
      notifyListeners();
    }
  }

  // 4. 完成测试提取结果
  Future complete() async {
    testResult = await testService.getTestResult();
  }

  Question getQuesById(String id) {
    return questionList.singleWhere((x) => x.quesId == id);
  }

  void changeIndex(int index) {
    if (index >= 0 && index < questionList.length) {
      this._index = index;
      notifyListeners();
    }
  }

  Future collect() async {
    if (current.isCollect) {
      await testService.cancelCollectQuestion(current.quesId);
      current.isCollect = false;
    } else {
      await testService.collectQuestion(current.quesId);
      current.isCollect = true;
    }
    notifyListeners();
  }
}
